/**
 * 管理后台中心首页.
 * @type {Vue}
 */
let vmManageHosts = new Vue({
    el: '#manage-hosts',
    data () {
        let validateIpv4 =  (rule, value, callback) => {
            if (QiStringUtils.isIpv4(value)) {
                callback();
            } else {
                callback(new Error(rule.message));
            }
        };

        let validateIpv4Batch = (rule, value, callback) => {
            if (QiStringUtils.isBlank(value)) {
                callback(new Error(rule.message));
                return;
            }
            let lineArr = value.split("\n");
            for (let i=0; i < lineArr.length; i++) {
                let colArr = lineArr[i].split(':');
                if (colArr.length != 2) {
                    callback(new Error(rule.message + ', 行：' + (i+1)))
                    return;
                }
                if (!QiStringUtils.isIpv4(colArr[0])) {
                    callback(new Error(rule.message + ', 行：' + (i+1)))
                    return;
                }
                if (colArr[1] < 1 || colArr[1] > 127) {
                    callback(new Error(rule.message + ', 行：' + (i+1)))
                    return;
                }
            }

            callback();
        };

        return {
            netList: [],
            //列表所需数据
            formQuery: {
                keyword: ''
            },
            listLoading: false,
            tableData : [],
            page: {
                current: 1,
                total: 0,
                page:1,
                pageSize:20
            },
            selectRows: [],

            //新增|修改
            isNew: false,
            dialogFormVisible: false,
            form: {
                IP: '',
                port: 80
            },
            tmpForm: {
                IP: '',
                port: 80
            },
            maskList: [],
            rules: {
                IP: [
                    { required: true, message: '请输入IP地址', trigger: 'blur' },
                    { validator: validateIpv4, message: '不是正确的IPV4地址' }
                ],
                port: [
                    { required: true, message: '请选择子网掩码', trigger: 'blur' }
                ]
            },

            //修改状态
            dialogBatchFormVisible: false,
            batchForm: {
                ipTxt: ''
            },
            batchFormTmp: {
                ipTxt: ''
            },
            batchRules: {
                ipTxt: [
                    { required: true, message: '请输入IP地址分配信息', trigger: 'blur' },
                    { validator: validateIpv4Batch, message: '不是正确的IPV4地址' }
                ]
            }

        }
    },
    methods: {
        pageLoad () {
            this.loadData();
        },
        /**
         * 架载统计数据.
         */
        loadData () {
            this.listLoading = true;
            let url = '/api/manage/hosts?';
            let param = $.extend({}, this.formQuery, {page: this.page.page, size: this.page.pageSize});
            url += QiServletUtils.mapToQueryString(param);
            url += (iFrameToken ? iFrameToken : ('&iframe-token=' + iFrameToken))
            QiRestClient.get(url, (data) => {
                this.tableData = data.items;
                this.page.total = data.total;
                this.listLoading = false;
            }, (data) => {
                this.$message.error(data.message);
                this.listLoading = false;
            });
        },
        /**
         * 查询触发.
         */
        onQuery () {
            this.page.current = 1;
            this.page.page = 1;
            this.loadData();
        },
        /**
         * 分页触发事件.
         * @param val
         */
        handleCurrentChange (val) {
            this.page.page = val;
            console.log("当前页数："+val);
            this.loadData();
        },
        /**
         * 选择事件.
         */
        handleSelectionChange (val) {
            this.selectRows = val;
        },
        /**
         * 新增.
         */
        showAdd () {
            this.isNew = true;
            this.form = Object.assign({}, this.tmpForm);
            this.dialogFormVisible = true;
        },
        /**
         * 标注.
         * @param row
         */
        showEdit (row) {
            this.isNew = false;
            this.form = Object.assign({}, row);

            this.dialogFormVisible = true;
        },
        /**
         * 保存数据操作.
         */
        saveEdit () {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    let success =  (data) => {
                        this.$message.success('操作成功');
                        this.dialogFormVisible = false;
                        this.loadData();
                    };
                    let error = (data) => {
                        this.$message.error(data.message);
                    };

                    if (this.isNew) {
                        QiRestClient.post('/api/manage/hosts' + (iFrameToken ? iFrameToken : ('?iframe-token=' + iFrameToken)), this.form, success, error);
                    } else {
                        QiRestClient.put('/api/manage/hosts/' + this.form.IP + (iFrameToken ? iFrameToken : ('?iframe-token=' + iFrameToken)), this.form, success, error);
                    }
                }
            });
        },
        /**
         * 显示批量新增
         */
        showAddBatch () {
            this.batchForm = Object.assign({}, this.batchFormTmp);
            this.dialogBatchFormVisible = true;
        },
        /**
         * 保存批量新增.
         */
        saveBatchAdd () {
            this.$refs['batchForm'].validate((valid) => {
                if (valid) {
                    let success =  (data) => {
                        this.$message.success('操作成功');
                        this.dialogBatchFormVisible = false;
                        this.loadData();
                    };
                    let error = (data) => {
                        this.$message.error(data.message);
                    };

                    QiRestClient.post('/api/manage/hosts/actions/batch_add' + (iFrameToken ? iFrameToken : ('?iframe-token=' + iFrameToken)), this.batchForm, success, error);
                }
            });
        },
        /**
         * 删除选中域名.
         */
        deleteAll () {
            if (this.selectRows.length < 1) {
                this.$message.error('请选择需要删除的IPV6分配记录.');
                return;
            }
            this.$confirm('确定需要移除选中IPV6分配记录吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then( () => {
                let domains = [];
                this.selectRows.forEach((row) => {
                    domains.push(row.IP);
                });
                QiRestClient.post('/api/manage/hosts/actions/delete' + (iFrameToken ? iFrameToken : ('?iframe-token=' + iFrameToken)),  domains, () => {
                    this.$message.success('操作成功');
                    this.loadData();
                },  (data) => {
                    this.$message.error(data.message);
                })
            });
        },
        /**
         * 删除.
         * @param row
         */
        deleteMessage (row) {
            let self = this;
            this.$confirm('确定需要移除选中记录吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then( () => {
                QiRestClient.delete('/api/manage/hosts/' + row.IP + (iFrameToken ? iFrameToken : ('?iframe-token=' + iFrameToken)),  () => {
                    self.$message.success('操作成功');
                    self.loadData();
                },  (data) => {
                    self.$message.error(data.message);
                })
            });
        }
    },
    mounted () {
        this.pageLoad();
    }
});